<?php
namespace Apps\Common\Libs;
error_reporting(0);
use JPush\Model as M;
use JPush\JPushClient;
use JPush\JPushLog;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use JPush\Exception\APIConnectionException;
use JPush\Exception\APIRequestException;
use PhalconPlus\Common\Component;
use Apps\Common\Models\UserBase;
use Apps\Common\Models\UserMessage;

class Jpush extends Component
{
    private $param;
    
    private $MYSQLERROR=100;//数据库错误
    
    private $SUCCESS=200;//推送成功
    
    private $PUSHFAIL=300;//推送失败
    
    private $DATAERROR=400;
    
    /*推送方法  */
    
    public function push(){
    	if($this->param['type'] ===null || $this->param['ispushservice']===null || $this->param['phone']===null || $this->param['content'] ===null || $this->param['shop_id']===null){
    		return $this->returnResult($this->DATAERROR, '数据错误！');
    	}
    	if(strlen($this->param['phone'])!=11){
    		return $this->returnResult($this->DATAERROR, '数据错误！');
    	}
    	if($this->param['phone']==''){
    		return $this->returnResult($this->DATAERROR, '数据错误！');
    	}
    	$userinfo=UserBase::findFirst("user_account = ".$this->param['phone']);
    	if(!$userinfo){
    		return $this->returnResult($this->DATAERROR, '数据错误！');
    	}
    	$user_id=$userinfo->user_id;
    	$usermessage= new UserMessage();
    	$usermessage->user_id=$user_id;
    	if($this->param['ispushservice']==1){
    		$usermessage->is_read_b=0;
    	}else{
    		$usermessage->is_read_b=1;
    	}
    	$usermessage->message_content=$this->param['content'];
    	$usermessage->push_type=$this->param['type'];
    	$usermessage->message_state=1;
    	$usermessage->shop_id=$this->param['shop_id'];
    	$usermessage->from_user_name=1;
    	$usermessage->from_user_cover=1;
    	$usermessage->message_link_type = $this->param['message_link_type'];
    	$usermessage->message_link_data = $this->param['message_link_data'];
    	$this->db->begin();
    	$message_status=$usermessage->save();//添加数据到user_message
    	if(!$message_status){
    		$this->db->rollback();
    		return $this->returnResult($this->MYSQLERROR,"数据库错误");
    	}
    	/*推送至APP代码*/
    	$config = $this->di->get('appConfig')->jpush;
    	$app_key=$config->app_key;
    	$master_secret = $config->master_secret;
    	JPushLog::setLogHandlers([new StreamHandler('jpush.log', Logger::DEBUG)]);
    	$client = new JPushClient($app_key, $master_secret);
    	//easy push
    	try {
    		$result = $client->push()
    		->setPlatform(M\all)
    		->setAudience(M\alias([$user_id]))
    		->setNotification(M\notification($this->param['content']))
    		->setOptions(M\options(null, null, null, true, null))
    		->send();
    		if($result->isOk===true){
    			$this->db->commit();
    			return $this->returnResult($this->SUCCESS,"推送成功！");
    		}else{
    			$this->db->rollback();
    			return $this->returnResult($this->PUSHFAIL,"推送失败!");
    		}
    	} catch (APIRequestException $e) {
    		/* echo 'Push Fail.' . '<br>';
    		 echo 'Http Code : ' . $e->httpCode . '<br>';
    		echo 'code : ' . $e->code . '<br>';
    		echo 'message : ' . $e->message . '<br>';
    		echo 'Response JSON : ' . $e->json . '<br>';
    		echo 'rateLimitLimit : ' . $e->rateLimitLimit . '<br>';
    		echo 'rateLimitRemaining : ' . $e->rateLimitRemaining . '<br>';
    		echo 'rateLimitReset : ' . $e->rateLimitReset . '<br>';
    		exit; */
    		
    		$this->db->rollback();
    		return $this->returnResult($this->PUSHFAIL,"推送失败!");
    			
    	} catch (APIConnectionException $e) {
    		$this->db->rollback();
    		return $this->returnResult($this->PUSHFAIL,"推送失败!");
    			
    	}
    	/*the end*/
    
    }
    /*
     * $param array 推送数据
    * $param['type'] 推送类型 （1：预约；2：定单；3：新增员工；4：库存预警；5：新增客户;6:问题回答；7：美容院评论）
    * $param['ispushservice'] 是否推送到B端
    * $param['phone'] 被推送人手机号
    * $param['content'] 推送的消息
    * $param['shop_id] 分店ID
    *   */
    public function setval($param){
    	if($param['type'] ===null || $param['ispushservice']===null || $param['phone']===null || $param['content'] ===null || $param['shop_id']===null){
    		return $this->returnResult($this->DATAERROR, '数据错误！');
    	}
    	if(strlen($param['phone'])!=11){
    		return $this->returnResult($this->DATAERROR, '数据错误！');
    	}
    	if ($param['message_link_type'] == null || $param['message_link_data'] == null){
    	    return $this->returnResult($this->DATAERROR, '数据错误');
    	}
    	$this->param=$param;
    }
    
    /*返回数据
     * $status 返回状态
    * $message 返回消息
    * */
    private function returnResult($status,$message){
    	$array=[
    			'status'=>$status,
    			'message'=>$message
    	];
    	return json_encode($array);
    }
}
